#pragma once

#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/epoll.h>
#include <unistd.h>
#include <string>
#include <vector>
#include "Public.h"
#include "Socket.h"

namespace sevent{

class Address;
class Loop;

class Connect{
public:
	Connect();
	Connect(int fd, Address addr);
	Connect(int fd, Address addr, Loop* loop);
	~Connect();

	int read(void *buf, int len, int timeout);
	int write(void *buf, int len, int timeout);
//	int connect();
	bool alive(); //before IO
	bool inUsing(); //before Accept
	int close();
	int shutdown();

	int fd(){return _fd;}
	connectStatus status(){return _status;}

	struct timeval connectTime(){return _connectTime;}
	struct timeval lastActiveTime(){return _lastActiveTime;}
	Address &peerAddr(){return _peerAddr;}
	Address &addr(){return _addr;}

	void setConnectTime(struct timeval t){_connectTime = t;}
	void setLastActiveTime(struct timeval t){_lastActiveTime = t;}
	void setPeerAddr(Address addr){_peerAddr = addr;}
	void setFd(int fd){_fd = fd;}
	void setStatus(connectStatus s){_status = s;}

	int addCount();
	int subCount();
	//int addCount(){return __sync_add_and_fetch(&_count, 1);}
	//int subCount(){return __sync_sub_and_fetch(&_count, 1);}
	int clearCount(){_count = 0;}
	int count(){return _count;}
	
	Loop* getLoop(){return _loop;}
	void setLoop(Loop *loop){_loop = loop;}

	int lock();
	int unLock();
private:
	Loop* _loop;

	struct timeval _connectTime;
	struct timeval _lastActiveTime;
	Address _peerAddr;
	Address _addr;
	int _fd;
	int _count; //-1 means not use; 0 means just Accept, but no Task using it now
	connectStatus _status;

	pthread_mutex_t _mutex; //__sync_sub_and_fetch seems enought. but just try this
};


}

